<?php
$sanitize_all_escapes = true;
$fake_register_globals = false;
if (!isset($_REQUEST['medico']))
    session_start();

$landingpage = "index.php?site=" . $_SESSION['site_id'];
if (isset($_SESSION['pid']) && isset($_SESSION['patient_portal_onsite'])) {
    $pid = $_SESSION['pid'];
} else {
    if (!isset($_REQUEST['medico'])) {
        session_destroy();
        header('Location: ' . $landingpage . '&w');
        exit;
    }
}
$ignoreAuth = true;
include_once('../interface/globals.php');
require_once("$srcdir/acl.inc");
require_once("$srcdir/options.inc.php");
require_once("$srcdir/formatting.inc.php");
require_once("$srcdir/erx_javascript.inc.php");

/*echo "<pre>";
    print_r($SESSION);
echo "</pre>";*/

// Session pid must be right or bad things can happen when demographics are saved!
//
include_once("$srcdir/pid.inc");

if (isset($_REQUEST['medico']))
    $pid = $_REQUEST['set_pid'];
$medico = "";
$medicoIni = "";
if (isset($_REQUEST['medico'])) {
    $medico = "&medico=1&set_pid=" . $pid;
    $medicoIni = "?medico=1&set_pid=" . $pid;
}

setpid($pid);
include_once("$srcdir/patient.inc");

$result = getPatientData($pid, "*, DATE_FORMAT(DOB,'%Y-%m-%d') as DOB_YMD");
$result2 = getEmployerData($pid);

$CPR = 4; // cells per row
// $statii = array('married','single','divorced','widowed','separated','domestic partner');
// $langi = getLanguages();
// $ethnoraciali = getEthnoRacials();
// $provideri = getProviderInfo();

$insurancei = getInsuranceProviders();

$fres = sqlStatement("SELECT * FROM layout_options " .
        "WHERE form_id = 'DEM' AND uor > 0 " .
        "ORDER BY group_name, seq");
?>
<html>
    <head>

        <style>

            #tabs{

            }

            #tabs .ui-tabs .ui-tabs-panel
            {
                background: none !important;
                border: none !important;
                display: block;
                min-height: 110px;
                padding: 20px 20px 40px;
                position: relative;
            }

            #tabs .ui-tabs-active {
                background: #43ACA4;
                color: #ffffff;
            }

            #tabs .ui-widget-header{
                background: none !important;
                border: 0px !important;
            }
            div.section {
                border: solid;
                border-width: 1px;
                border-color: #0000ff;
                margin: 0 0 0 10pt;
                padding: 5pt;
            }

            #demographics_form .text > input {
                font-size: 14px;
                margin-right: 5px;
                padding: 3px;
                width: 175px;
            }

            #demographics_form .label {
                font-size: 14px;
                margin-right: 5px;
            }

        </style> 

        <link rel="stylesheet" href="<?php echo $web_root; ?>/library/js/ui-lightness/jquery-ui-1.10.3.custom.min.css" type="text/css"/>
        <link rel="stylesheet" href="<?php echo $web_root; ?>/patients/css/nightingale.css" type="text/css"/>
        <link rel="stylesheet" type="text/css" href="<?php echo $web_root; ?>/interface/themes/jquery.fancybox.css?v=2.1.5" media="screen"/>
        <link rel="stylesheet" href="<?php echo $web_root; ?>/patients/css/jquery.autocomplete.css" type="text/css"/>
        
        <script type="text/javascript" src="<?php echo $web_root; ?>/library/js/jquery-1.10.0.min.js"></script>        
        <script type="text/javascript" src="<?php echo $web_root; ?>/library/js/jquery-ui-1.10.3.custom.min2.js"></script>

        <script type="text/javascript" src="<?php echo $web_root; ?>/library/dialog.js"></script>
        <script type="text/javascript" src="<?php echo $web_root; ?>/library/js/jquery.fancybox.pack.js"></script>
        <script type="text/javascript" src="<?php echo $web_root; ?>/patients/js/jquery.mask.min.js"></script>
        <script type="text/javascript" src="<?php echo $web_root; ?>/patients/js/jquery.autocomplete.js"></script>

        <script type="text/javascript">
            $(document).ready(function() {
                $("#form_DOB").mask("99-99-9999");
                
                $('#tabs').tabs();
                $("#tabs").css("display", "block");

                $(".medium_modal").fancybox({
                    'overlayOpacity': 0.0,
                    'showCloseButton': true,
                    'frameHeight': 460,
                    'frameWidth': 650
                });
				
                $("#form_DOB").datepicker({
                    showOn: "button",
                    buttonImage: "<?php echo $web_root; ?>/patients/images/calendar-green.gif",
                    dateFormat: 'dd-mm-yy',
                    changeMonth: true,
                    changeYear: true,
                    buttonImageOnly: true
                });          

				$("#form_deceased_date").datepicker({
                    showOn: "button",
                    buttonImage: "<?php echo $web_root; ?>/patients/images/calendar-green.gif",
                    dateFormat: 'dd-mm-yy',
                    changeMonth: true,
                    changeYear: true,
                    buttonImageOnly: true
                });

                //$(".ui-datepicker-trigger").after(" <span>(dd-mm-aaaa)</span> ");

                /*var date = $('#form_DOB').val();
                 alert("<?php echo toDateView("+date+"); ?>");
                 alert(date);*/

<?php for ($i = 1; $i <= 3; $i++) { ?>
                    $("#form_i<?php echo $i ?>subscriber_relationship").change(function() {
                        auto_populate_employer_address<?php echo $i ?>();
                    });
<?php } ?>

                //$(".ui-datepicker-trigger").after(" <span>(dd-mm-aaaa)</span> ");


                $("#cancel").click(function() {
                    parent.jQuery.fancybox.close();
                });
				
                        $("#form_ocupaciones2").autocomplete("<?php echo $web_root; ?>/interface/ocupaciones_autocomplete.php",
                        {
                            minChars: 3,
                            matchSubset: 1,
                            matchContains: 1,
                            selectFirst: false,
                            cacheLength: 10,
                            autoFill: false,
                            onItemSelect: function(li) {
                                $("#form_ocupaciones2").val($("<div>").html(li.selectValue).text());
                            }
                        });

                $("#form_ocupaciones2").result(function(event, data, formatted) {
        //            $("#form_patient").val(data[0]);
                    $("#ocupacion").val(data[1]);
                });
				
				
				$("#form_empresaSeguro").autocomplete("<?php echo $web_root; ?>/interface/seguros_autocomplete.php",
                        {
                            minChars: 3,
                            matchSubset: 1,
                            matchContains: 1,
                            selectFirst: false,
                            cacheLength: 10,
                            autoFill: false,
                            onItemSelect: function(li) {
                                $("#form_empresaSeguro").val($("<div>").html(li.selectValue).text());
                            }
                        });

						$("#form_empresaSeguro").result(function(event, data, formatted) {
				//            $("#form_patient").val(data[0]);
							$("#seguro").val(data[1]);
						});
				
				$("#form_departamento").width("140px");
                                $("#form_seguro").width("140px");
                                //$("#form_ocupaciones").width("140px");
				$("#form_departamento").on('change', function() {
						var url = "location_check.php";
						$.post( url+"?check_muni=1&id="+this.value, function( data ) {
							$( "#form_municipio" ).html( data );
							//alert(data);
						});
				});
				
				$("#form_municipio").on('change', function() {
						var url = "location_check.php";
						$.post( url+"?check_centro=1&id="+this.value, function( data ) {
							$( "#form_centro_p" ).html( data );
							//alert(data);
						});
				});
	
            });

            var mypcc = '<?php echo $GLOBALS['phone_country_code'] ?>';

            //code used from http://tech.irt.org/articles/js037/
            function replace(string, text, by) {
                // Replaces text with by in string
                var strLength = string.length, txtLength = text.length;
                if ((strLength == 0) || (txtLength == 0))
                    return string;

                var i = string.indexOf(text);
                if ((!i) && (text != string.substring(0, txtLength)))
                    return string;
                if (i == -1)
                    return string;

                var newstr = string.substring(0, i) + by;

                if (i + txtLength < strLength)
                    newstr += replace(string.substring(i + txtLength, strLength), text, by);

                return newstr;
            }

            function upperFirst(string, text) {
                return replace(string, text, text.charAt(0).toUpperCase() + text.substring(1, text.length));
            }

<?php for ($i = 1; $i <= 3; $i++) { ?>
                function auto_populate_employer_address<?php echo $i ?>() {
                    var f = document.demographics_form;
                    if (f.form_i<?php echo $i ?>subscriber_relationship.options[f.form_i<?php echo $i ?>subscriber_relationship.selectedIndex].value == "self")
                    {
                        f.i<?php echo $i ?>subscriber_fname.value = f.form_fname.value;
                        f.i<?php echo $i ?>subscriber_mname.value = f.form_mname.value;
                        f.i<?php echo $i ?>subscriber_lname.value = f.form_lname.value;
                        f.i<?php echo $i ?>subscriber_street.value = f.form_street.value;
                        f.i<?php echo $i ?>subscriber_city.value = f.form_city.value;
                        f.form_i<?php echo $i ?>subscriber_state.value = f.form_state.value;
                        f.i<?php echo $i ?>subscriber_postal_code.value = f.form_postal_code.value;
                        if (f.form_country_code)
                            f.form_i<?php echo $i ?>subscriber_country.value = f.form_country_code.value;
                        f.i<?php echo $i ?>subscriber_phone.value = f.form_phone_home.value;
                        f.i<?php echo $i ?>subscriber_DOB.value = f.form_DOB.value;
                        if (typeof f.form_ss != "undefined")
                        {
                            f.i<?php echo $i ?>subscriber_ss.value = f.form_ss.value;
                        }
                        f.form_i<?php echo $i ?>subscriber_sex.value = f.form_sex.value;
                        f.i<?php echo $i ?>subscriber_employer.value = f.form_em_name.value;
                        f.i<?php echo $i ?>subscriber_employer_street.value = f.form_em_street.value;
                        f.i<?php echo $i ?>subscriber_employer_city.value = f.form_em_city.value;
                        f.form_i<?php echo $i ?>subscriber_employer_state.value = f.form_em_state.value;
                        f.i<?php echo $i ?>subscriber_employer_postal_code.value = f.form_em_postal_code.value;
                        if (f.form_em_country)
                            f.form_i<?php echo $i ?>subscriber_employer_country.value = f.form_em_country.value;
                    }
                }

<?php } ?>

            function popUp(URL) {
                day = new Date();
                id = day.getTime();
                top.restoreSession();
                eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=400,height=300,left = 440,top = 362');");
            }

            function checkNum() {
                var re = new RegExp();
                re = /^\d*\.?\d*$/;
                str = document.demographics_form.monthly_income.value;
                if (re.exec(str))
                {
                } else {
                    alert("<?php xl('Please enter a monetary amount using only numbers and a decimal point.', 'e'); ?>");
                }
            }

            // Indicates which insurance slot is being updated.
            var insurance_index = 0;

            // The OnClick handler for searching/adding the insurance company.
            function ins_search(ins) {
                insurance_index = ins;
                return false;
            }

            // The ins_search.php window calls this to set the selected insurance.
            function set_insurance(ins_id, ins_name) {
                var thesel = document.forms[0]['i' + insurance_index + 'provider'];
                var theopts = thesel.options; // the array of Option objects
                var i = 0;
                for (; i < theopts.length; ++i) {
                    if (theopts[i].value == ins_id) {
                        theopts[i].selected = true;
                        return;
                    }
                }
                // no matching option was found so create one, append it to the
                // end of the list, and select it.
                theopts[i] = new Option(ins_name, ins_id, false, true);
            }

            // This capitalizes the first letter of each word in the passed input
            // element.  It also strips out extraneous spaces.
            function capitalizeMe(elem) {
                var a = elem.value.split(' ');
                var s = '';
                for (var i = 0; i < a.length; ++i) {
                    if (a[i].length > 0) {
                        if (s.length > 0)
                            s += ' ';
                        s += a[i].charAt(0).toUpperCase() + a[i].substring(1);
                    }
                }
                elem.value = s;
            }

            function divclick(cb, divid) {
                var divstyle = document.getElementById(divid).style;
                if (cb.checked) {
                    divstyle.display = 'block';
                } else {
                    divstyle.display = 'none';
                }
                return true;
            }

            // Compute the length of a string without leading and trailing spaces.
            function trimlen(s) {
                var i = 0;
                var j = s.length - 1;
                for (; i <= j && s.charAt(i) == ' '; ++i)
                    ;
                for (; i <= j && s.charAt(j) == ' '; --j)
                    ;
                if (i > j)
                    return 0;
                return j + 1 - i;
            }

            function validate(f) {
                var errCount = 0;
                var errMsgs = new Array();
<?php generate_layout_validation('DEM'); ?>

                var msg = "";
                msg += "<?php xl('The following fields are required', 'e'); ?>:\n\n";
                for (var i = 0; i < errMsgs.length; i++) {
                    msg += errMsgs[i] + "\n";
                }
                msg += "\n<?php xl('Please fill them in before continuing.', 'e'); ?>";

                if (errMsgs.length > 0) {
                    alert(msg);
                }

                //Patient Data validations
<?php if ($GLOBALS['erx_enable']) { ?>
                    alertMsg = '';
                    for (i = 0; i < f.length; i++) {
                        if (f[i].type == 'text' && f[i].value)
                        {
                            if (f[i].name == 'form_fname' || f[i].name == 'form_mname' || f[i].name == 'form_lname')
                            {
                                alertMsg += checkLength(f[i].name, f[i].value, 35);
                                alertMsg += checkUsername(f[i].name, f[i].value);
                            }
                            else if (f[i].name == 'form_street' || f[i].name == 'form_city')
                            {
                                alertMsg += checkLength(f[i].name, f[i].value, 35);
                                alertMsg += checkAlphaNumericExtended(f[i].name, f[i].value);
                            }
                            else if (f[i].name == 'form_phone_home')
                            {
                                alertMsg += checkPhone(f[i].name, f[i].value);
                            }
                        }
                    }
                    if (alertMsg)
                    {
                        alert(alertMsg);
                        return false;
                    }
<?php } ?>
                //return false;

                // Some insurance validation.
                for (var i = 1; i <= 3; ++i) {
                    subprov = 'i' + i + 'provider';
                    if (!f[subprov] || f[subprov].selectedIndex <= 0)
                        continue;
                    var subpfx = 'i' + i + 'subscriber_';
                    var subrelat = f['form_' + subpfx + 'relationship'];
                    var samename =
                            f[subpfx + 'fname'].value == f.form_fname.value &&
                            f[subpfx + 'mname'].value == f.form_mname.value &&
                            f[subpfx + 'lname'].value == f.form_lname.value;
                    var ss_regexp = /[0-9][0-9][0-9]-?[0-9][0-9]-?[0-9][0-9][0-9][0-9]/;
                    var samess = true;
                    var ss_valid = false;
                    if (typeof f.form_ss != "undefined")
                    {
                        samess = f[subpfx + 'ss'].value == f.form_ss.value;
                        ss_valid = ss_regexp.test(f[subpfx + 'ss'].value) && ss_regexp.test(f.form_ss.value);
                    }
                    if (subrelat.options[subrelat.selectedIndex].value == "self") {
                        if (!samename) {
                            if (!confirm("<?php echo xls('Subscriber relationship is self but name is different! Is this really OK?'); ?>"))
                                return false;
                        }
                        if (!samess && ss_valid) {
                            if (!confirm("<?php echo xls('Subscriber relationship is self but SS number is different!') . " " . xls("Is this really OK?"); ?>"))
                                return false;
                        }
                    } // end self
                    else {
                        if (samename) {
                            if (!confirm("<?php echo xls('Subscriber relationship is not self but name is the same! Is this really OK?'); ?>"))
                                return false;
                        }
                        if (samess && ss_valid) {
                            if (!confirm("<?php echo xls('Subscriber relationship is not self but SS number is the same!') . " " . xls("Is this really OK?"); ?>"))
                                return false;
                        }
                    } // end not self
                } // end for

                return errMsgs.length < 1;
            }

            function submitme() {
                var f = document.forms[0];
                if (validate(f)) {
//            top.restoreSession();
                    f.submit();
                }
            }

            // Onkeyup handler for policy number.  Allows only A-Z and 0-9.
            function policykeyup(e) {
                var v = e.value.toUpperCase();
                for (var i = 0; i < v.length; ++i) {
                    var c = v.charAt(i);
                    if (c >= '0' && c <= '9')
                        continue;
                    if (c >= 'A' && c <= 'Z')
                        continue;
                    if (c == '*')
                        continue;
                    if (c == '-')
                        continue;
                    if (c == '_')
                        continue;
                    if (c == '(')
                        continue;
                    if (c == ')')
                        continue;
                    if (c == '#')
                        continue;
                    v = v.substring(0, i) + v.substring(i + i);
                    --i;
                }
                e.value = v;
                return;
            }
        </script>
    </head>

    <body class="body_top" style="width: 800px; height: 320px;">
        <form action='<?php echo $web_root; ?>/patients/demographics_save.php<?php echo $medicoIni; ?>' id='demographics_form' name='demographics_form' method='post' onsubmit='return validate(this)'>
            <input type='hidden' name='mode' value='save' />
            <input type='hidden' name='db_id' value="<?php echo $result['id'] ?>" />
            <input type='hidden' name='form_ocupaciones' id='form_ocupaciones'></input>

            <div class="borde_normal">
                <span class="historial_paciente"><i class="icon-user" style="font-size: 1.4em;"></i> <?php xl('Current Patient', 'e'); ?> </span>
                <?php if(!acl_check('admin','adm_cnf')){ ?>
                <a href="javascript:submitme();" class='css_button'><span><i class="icon-ok-sign" style="font-size: 25px;"></i> <?php xl('Save', 'e'); ?></span></a>
                <?php } ?>
                <a class="css_button" id="cancel" href=""><span><i style="font-size: 25px;" class="icon-remove-sign"></i> Cancelar</span></a>
            </div>

            <div id="tabs" style="display: none;">

                <?php

                function end_cell() {
                    global $item_count, $cell_count;
                    if ($item_count > 0) {
                        echo "</td>";
                        $item_count = 0;
                    }
                }

                function end_row() {
                    global $cell_count, $CPR;
                    end_cell();
                    if ($cell_count > 0) {
                        for (; $cell_count < $CPR; ++$cell_count)
                            echo "<td></td>";
                        echo "</tr>\n";
                        $cell_count = 0;
                    }
                }

                function end_group() {
                    global $last_group;
                    if (strlen($last_group) > 0) {
                        end_row();
                        echo " </table>\n";
                        echo "</div>\n";
                    }
                }

                $last_group = '';
                $cell_count = 0;
                $item_count = 0;
                $display_style = 'block';

                $group_seq = 0; // this gives the DIV blocks unique IDs
                ?>

                <?php
                echo "<ul>";
                display_layout_tabs('DEM', $result, $result2);
                echo "</ul>";
                ?>
				
                <?php display_layout_tabs_data_editable('DEM', $result, $result2); ?>
				
				<input type="hidden" name="seguro" id="seguro"></input>
				<input type="hidden" name="ocupacion" id="ocupacion"></input>
				
        </form>

        <script language="JavaScript">

            // fix inconsistently formatted phone numbers from the database
            var f = document.forms[0];
            /* if (f.form_phone_contact)
             phonekeyup(f.form_phone_contact, mypcc);
             if (f.form_phone_home)
             phonekeyup(f.form_phone_home, mypcc);
             if (f.form_phone_biz)
             phonekeyup(f.form_phone_biz, mypcc);
             if (f.form_phone_cell)
             phonekeyup(f.form_phone_cell, mypcc);*/

<?php if (!$GLOBALS['simplified_demographics']) { ?>
                /*  phonekeyup(f.i1subscriber_phone, mypcc);
                 phonekeyup(f.i2subscriber_phone, mypcc);
                 phonekeyup(f.i3subscriber_phone, mypcc);*/
<?php } ?>

<?php if ($GLOBALS['concurrent_layout'] && $set_pid) { ?>
                parent.left_nav.setPatient(<?php echo "'" . addslashes($result['fname']) . " " . addslashes($result['lname']) . "',$pid,'" . addslashes($result['pubpid']) . "','', ' " . xl('DOB') . ": " . oeFormatShortDate($result['DOB_YMD']) . " " . xl('Age') . ": " . getPatientAge($result['DOB_YMD']) . "'"; ?>);
                parent.left_nav.setRadio(window.name, 'dem');
<?php } ?>
        </script>
    </body>
</html>
